Example Assignment


Before you turn this problem in, make sure everything runs as expected. First, restart the kernel (in the menubar, select Kernel$\rightarrow$Restart) and then run all cells (in the menubar, select Cell$\rightarrow$Run All).

Make sure you fill in any place that says YOUR CODE HERE or "YOUR ANSWER HERE", as well as your name and collaborators below:


In [1]:
NAME = "Jane Doe"
COLLABORATORS = "n/a"


In [2]:
# import plotting libraries
%matplotlib inline
import matplotlib.pyplot as plt

Problem 1

Write a function that returns a list of numbers, such that $x_i=i^2$, for $1\leq i \leq n$. Make sure it handles the case where $n<1$ by raising a ValueError.


In [3]:
def squares(n):
    """Compute the squares of numbers from 1 to n, such that the 
    ith element of the returned list equals i^2.
    
    """
    return [i**2 for i in xrange(1, n + 1)]

Your function should print [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] for $n=10$. Check that it does:


In [4]:
squares(10)


Out[4]:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In [5]:
"""Check that squares returns the correct output for several inputs"""
from nbgrader.tests import assert_equal
assert_equal(squares(1), [1])
assert_equal(squares(2), [1, 4])
assert_equal(squares(10), [1, 4, 9, 16, 25, 36, 49, 64, 81, 100])
assert_equal(squares(11), [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121])


Score: 1.0 / 1.0

In [6]:
"""Check that squares raises an error for invalid inputs"""
from nbgrader.tests import assert_raises
assert_raises(ValueError, squares, 0)
assert_raises(ValueError, squares, -4)


Score: 0.0 / 1.0
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-6-82972a2b7720> in <module>()
      1 """Check that squares raises an error for invalid inputs"""
      2 from nbgrader.tests import assert_raises
----> 3 assert_raises(ValueError, squares, 0)
      4 assert_raises(ValueError, squares, -4)

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.pyc in assertRaises(self, excClass, callableObj, *args, **kwargs)
    473             return context
    474         with context:
--> 475             callableObj(*args, **kwargs)
    476 
    477     def _getAssertEqualityFunc(self, first, second):

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.pyc in __exit__(self, exc_type, exc_value, tb)
    114                 exc_name = str(self.expected)
    115             raise self.failureException(
--> 116                 "{0} not raised".format(exc_name))
    117         if not issubclass(exc_type, self.expected):
    118             # let unexpected exceptions pass through

AssertionError: ValueError not raised

Problem 2

Part A

Using your squares function, write a function that computes the sum of the squares of the numbers from 1 to $n$. Your function should call the squares function -- it should NOT reimplement its functionality.


In [7]:
def sum_of_squares(n):
    """Compute the sum of the squares of numbers from 1 to n."""
    return sum(squares(n))

The sum of squares from 1 to 10 should be 385. Verify that this is the answer you get:


In [8]:
sum_of_squares(10)


Out[8]:
385

In [9]:
"""Check that sum_of_squares returns the correct answer for various inputs."""
assert_equal(sum_of_squares(1), 1)
assert_equal(sum_of_squares(2), 5)
assert_equal(sum_of_squares(10), 385)
assert_equal(sum_of_squares(11), 506)


Score: 0.5 / 0.5

In [10]:
"""Check that sum_of_squares relies on squares."""
orig_squares = squares
del squares
try:
    assert_raises(NameError, sum_of_squares, 1)
except AssertionError:
    raise AssertionError("sum_of_squares does not use squares")
finally:
    squares = orig_squares


Score: 0.5 / 0.5

Part B

Using LaTeX math notation, write out the equation that is implemented by your sum_of_squares function.

$\sum_{i=1}^n i^2$

Part C

Create a plot of the sum of squares for $n=1$ to $n=15$. Make sure to appropriately label the $x$-axis and $y$-axis, and to give the plot a title. Set the $x$-axis limits to be 1 (minimum) and 15 (maximum).


In [11]:
fig, ax = plt.subplots() # do not delete this line!
x = range(1, 16)
y = [sum_of_squares(x[i]) for i in xrange(len(x))]
ax.plot(x, y)
ax.set_title("Sum of squares from 1 to $n$")
ax.set_xlabel("$n$")
ax.set_ylabel("sum")


Out[11]:
<matplotlib.text.Text at 0x10961a990>

In [12]:
"""Check that the axis limits are correct."""
assert_equal(ax.get_xlim(), (1.0, 15.0))


Score: 0.0 / 0.166666666667
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-12-7eaa2f5456f5> in <module>()
      1 """Check that the axis limits are correct."""
----> 2 assert_equal(ax.get_xlim(), (1.0, 15.0))

/usr/local/lib/python2.7/site-packages/nose/tools/trivial.pyc in eq_(a, b, msg)
     27     """
     28     if not a == b:
---> 29         raise AssertionError(msg or "%r != %r" % (a, b))
     30 
     31 

AssertionError: (0.0, 16.0) != (1.0, 15.0)

In [13]:
"""Check that the xlabel is set."""
from nbgrader.tests import assert_unequal
assert_unequal(ax.get_xlabel(), "", "xlabel not set")


Score: 0.166666666667 / 0.166666666667

In [14]:
"""Check that the ylabel is set."""
assert_unequal(ax.get_ylabel(), "", "ylabel not set")


Score: 0.166666666667 / 0.166666666667

In [15]:
"""Check that the title is set."""
assert_unequal(ax.get_title(), "", "title not set")


Score: 0.166666666667 / 0.166666666667

In [16]:
"""Check that the correct xdata was used."""
from nbgrader.tests import assert_allclose, assert_same_shape

lines = ax.get_lines()
assert_equal(len(lines), 1)

xdata = lines[0].get_xdata()
xdata_correct = np.arange(1, 16)
assert_same_shape(xdata, xdata_correct)
assert_allclose(xdata, xdata_correct)


Score: 0.166666666667 / 0.166666666667

In [17]:
"""Check that the correct ydata was used."""
lines = ax.get_lines()
assert_equal(len(lines), 1)

xdata = lines[0].get_xdata()
ydata = lines[0].get_ydata()
ydata_correct = [sum_of_squares(x) for x in xdata]
assert_same_shape(ydata, ydata_correct)
assert_allclose(ydata, ydata_correct)


Score: 0.166666666667 / 0.166666666667